import { createSlice, PayloadAction } from '@reduxjs/toolkit';

export interface MerchantIdentity {
  id: number;
  entity_type: number; // 实体类型
  entity_name: string; // 实体名称，用于显示
  status: number; // 状态
  name?: string; // 兼容字段
  type?: string; // 兼容字段
  description?: string;
  category?: string; // 管理员身份、企业身份等
  [key: string]: any;
}

interface MerchantState {
  currentEntity: MerchantIdentity | null;
  list: MerchantIdentity[];
  loading: boolean;
}

const initialState: MerchantState = {
  currentEntity: null,
  list: [],
  loading: false,
};

const merchantSlice = createSlice({
  name: 'merchant',
  initialState,
  reducers: {
    setMerchantList: (state, action: PayloadAction<MerchantIdentity[]>) => {
      state.list = action.payload;
    },
    setCurrentEntity: (state, action: PayloadAction<MerchantIdentity>) => {
      state.currentEntity = action.payload;
      // 同时存储到localStorage
      localStorage.setItem('currentMerchantEntity', JSON.stringify(action.payload));
    },
    setLoading: (state, action: PayloadAction<boolean>) => {
      state.loading = action.payload;
    },
    clearMerchantData: (state) => {
      state.currentEntity = null;
      state.list = [];
      state.loading = false;
      localStorage.removeItem('currentMerchantEntity');
      localStorage.removeItem('merchantIdentity');
    },
  },
});

export const { setMerchantList, setCurrentEntity, setLoading, clearMerchantData } = merchantSlice.actions;
export default merchantSlice.reducer;
